#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>

void Usage(char *args)
{
    std::cout << "Usage : " << args << " server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock failed : " << errno << std::endl;
        return 2;
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    if (connect(sock, (sockaddr *)&server, sizeof(server)) < 0)
    {
        return 3;
    }

    while (1)
    {
        std::cout << "Please Enter# ";
#define NUM 1024
        char buf[NUM] = {0};

        fgets(buf, NUM - 1, stdin);
        write(sock, buf, strlen(buf));

        ssize_t sz = read(sock, buf, NUM - 1);
        if (sz > 0)
        {
            buf[sz] = 0;
            std::cout << buf << std::endl;
        }
        else if (sz == 0)
        {
            std::cout << "对端关闭" << std::endl;
            return 4;
        }
        else 
        {
            return 5;
        }
    }
}